package com.javatiaocao.myblog.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.mapper.PrivateWordMapper;
import com.javatiaocao.myblog.mapper.UserMapper;
import com.javatiaocao.myblog.model.PrivateWord;
import com.javatiaocao.myblog.model.User;
import com.javatiaocao.myblog.service.PrivateWordService;
import com.javatiaocao.myblog.utils.DataMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PrivateWordServiceImpl implements PrivateWordService {
    @Autowired
    PrivateWordMapper privateWordMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public DataMap getAllPrivateWord() {
        /**
         *
         *data['result']JSONObject result--JSONObject obj --JSONOArray content --JSONObject obj1
         *              obj['publisher'] obj
         *              obj['content']  obj1['replyContent']
         *                              obj1['publisherDate']
         *                              obj1['id']
         *                              obj1['privateWord']
         * **/
        JSONObject returnObject = new JSONObject();//最终返回
        JSONArray returnArray = new JSONArray();//‘result’的对象

        List<PrivateWord> privateWordList = privateWordMapper.getAllPrivateWord();
        List<User> userList = privateWordMapper.getAllPublisherId();
        if(privateWordList == null){
            return DataMap.fail(CodeType.COMMENT_BLANK);
        }

//        User user = userMapper.selectUserById(privateWordList.get(0).getPublisherId());

        if (userList == null ){
            return DataMap.fail(CodeType.COMMENT_BLANK);
        }
        for (User user : userList) {
            JSONObject publisherObject = new JSONObject();
            publisherObject.put("publisher",user.getUsername());
            JSONArray jsonArray = new JSONArray();

            for (PrivateWord privateWord : privateWordList) {

                JSONObject contentObject = new JSONObject();
                contentObject.put("replyContent",privateWord.getReplyContent());
                contentObject.put("publisherDate",privateWord.getPublisherDate());
                contentObject.put("id",privateWord.getId());
                contentObject.put("privateWord",privateWord.getPrivateWord());
                jsonArray.add(contentObject);
            }

            publisherObject.put("content",jsonArray);
            returnArray.add(publisherObject);
        }

        returnObject.put("result",returnArray);

        return DataMap.success(CodeType.SUCCESS_STATUS).setData(returnObject);
    }
}
